package cn.tedu.mall.seckill.interceptor;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.seckill.service.impl.SeckillSkuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class RedisStockInterceptor implements SeckillInterceptor {
    /**
     * 每个sku都是一个秒杀订单提交的商品数据
     * 每个sku 在redis中同步了数据库的库存 seckill:sku:stock:2  100
     * 每次调用这个方法,对已经存在的库存数据做decr操作
     * 如果返回值是负数,拦截,抛异常
     *
     * @param seckillOrderAddDTO
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void seckillCommitCheck(SeckillOrderAddDTO seckillOrderAddDTO) {
        String skuStockKey = SeckillSkuServiceImpl.SECKILL_SKU_STOCK_PREFIX
                + seckillOrderAddDTO.getSeckillOrderItemAddDTO().getSkuId();
        //decr命令 减一操作,判断返回值
        //decr seckill:sku:stock:1
        Long decrement = stringRedisTemplate.opsForValue().decrement(skuStockKey);
        if (decrement < 0) {
            throw new CoolSharkServiceException(
                    ResponseCode.CONFLICT, "商品在redis减库存失败");
        }
    }
}
